/**
 * Funciones para drag & drop para las lineas
 */
function draggableOnDragStartUser(e) {
}

function droptargetOnDragEnterUser(e) {
}

function droptargetOnDragLeaveUser(e) {
}

function droptargetOnDropUser(e) {
    var data = e.draggable.element.data();
    var userId = data['userId'];
    var userName = data['userName'];
    var userCurp = data['userCurp'];
    var userNomina = data['userNomina'];
    var userAdmissionDate = data['userAdmissionDate'];
    
    if(!existTeamUser( userId )) {
        var teamUser = {
            id: kendo.guid(),
            team_id: appBosch.selectedTeam.id,
            user_id: userId,
            type: 1,
            full_name: userName,
            curp: userCurp,
            nomina: userNomina,
            admission_date: userAdmissionDate,
            line_id: appBosch.currVLineId
        };
        addTeamUser(teamUser);
    }
}

function addUserOnClick(e) {
    var data = e.item[0].childNodes[1].dataset;
    var userId = data['userId'];
    var userName = data['userName'];
    var userCurp = data['userCurp'];
    var userNomina = data['userNomina'];
    var userAdmissionDate = data['userAdmissionDate'];
    if( !existTeamUser( userId ) ) {
        var teamUser = {
            id: kendo.guid(),
            team_id: appBosch.selectedTeam.id,
            user_id: userId,
            type: 1,
            full_name: userName,
            curp: userCurp,
            nomina: userNomina,
            admission_date: userAdmissionDate,
            line_id: appBosch.currVLineId
        };
        addTeamUser(teamUser);
    }
    e.preventDefault();
}

function loadTeamUsers(url, userErrors) {
    var containerTeamUsers = $('div.container-users div.my');
    containerTeamUsers.html('');
    $.getJSON(url, function(data) {
        var teamUsers = data.users !== undefined ? data.users : [];
        appBosch.myTeamUsers = [];
        appBosch.myTeamLeaders = 0;
        teamUsers.forEach(function(teamUser) {
            if (teamUser.leader == 1) {
                appBosch.myTeamLeaders++;
            }
            appBosch.myTeamUsers.push(teamUser);
            var code = appBosch.templateTeamUser(teamUser);
            containerTeamUsers.append(code);
        });
        $( '#asocLength' ).html( appBosch.templateAsocLength( { count: appBosch.myTeamUsers.length, leaders: appBosch.myTeamLeaders } ) );
    });
}

$(document).ready(function() {
    /// Cargamos los templates
    appBosch.templateUser           = kendo.template($('#templateUser').html());
    appBosch.templateTeamUser       = kendo.template($('#templateTeamUser').html());
    appBosch.dlgTemplateAddErrors   = kendo.template($('#templateAddErrors').html());
    //Drag & Drop para los usuarioss
    $('div.container-users div.my').kendoDropTarget({
        dragenter: droptargetOnDragEnterUser,
        dragleave: droptargetOnDragLeaveUser,
        drop: droptargetOnDropUser
    });
    
    $('div.container-users').on('click', 'div.teamUser i.destroy', function(e) {
        var divTeamUser = $(e.target).parents('.teamUser');
        divTeamUser.hide();
        var id = divTeamUser.data('id');
        var index = -1;
        for(var i = 0; i<appBosch.myTeamUsers.length;i++){
            var teamUser = appBosch.myTeamUsers[i];
            if( teamUser.id === id ){
                index = i;
                if(teamUser.leader === true) {
                    appBosch.myTeamLeaders--;
                }
                break;
            }
        }
        if( index !== -1 ){
            appBosch.myTeamUsers.splice(index,1);
        }        
        $.getJSON(appBosch.urlTeamUsersDestroy,
                {
                    id: id
                }).success(function(){
                    $( '#asocLength' ).html( appBosch.templateAsocLength( { count: appBosch.myTeamUsers.length, leaders: appBosch.myTeamLeaders } ) );
                });
    });

    $('div.container-users').on('click', 'div.teamUser td.icon, div.teamUser td.detail, div.teamUser i.fa-star', function(e) {
        var divTeamUser = $(e.target).closest('.teamUser');
        var id = divTeamUser.data('id');
        $.post(appBosch.urlToggleUserLeader + '/' + id, {}, function (resp) {
            if (resp === true) {
                var star = divTeamUser.find('.fa-star');
                star.toggleClass('leader');
                for(var i = 0; i<appBosch.myTeamUsers.length;i++){
                    var teamUser = appBosch.myTeamUsers[i];
                    if( teamUser.id === id ){
                        teamUser.leader = !teamUser.leader;
                        break;
                    }
                }
                if (star.hasClass('leader')) {
                    appBosch.myTeamLeaders++;
                } else {
                    appBosch.myTeamLeaders--;
                }
                $( '#asocLength' ).html( appBosch.templateAsocLength( { count: appBosch.myTeamUsers.length, leaders: appBosch.myTeamLeaders } ) );
            }
        });
    });
});

function existTeamUser(userId){
    var exist = false;
    if (appBosch.myTeamUsers === undefined) {
        appBosch.myTeamUsers = [];
    }
    appBosch.myTeamUsers.forEach(function(teamUser) {
        if (teamUser.user_id === userId) {
            exist = true;
        }
    });
    return exist;
}

function addTeamUser(teamUser){
    $.getJSON(appBosch.urlTeamUsersCreate, teamUser, function(data){
        console.log(data);
        if( data.rc === '00' ){
            appBosch.myTeamUsers.push(teamUser);
            var teamUserCode = appBosch.templateTeamUser(teamUser);
            $('.container-users .my').append(teamUserCode);
            $( '#asocLength' ).html( appBosch.templateAsocLength( { count: appBosch.myTeamUsers.length } ) );
        }else{ 
            showDlgInsertErrors( {
                'msg': appBosch.qMessages.msgAddUsersDetails,
                'userErrors' : [{
                    'nomina':teamUser.nomina,
                    'ec': data.rc
                }]
            } );
        }        
    });
}

function existTeamUserByNomina(nomina){
    var exist = false;
    if (appBosch.myTeamUsers === undefined) {
        appBosch.myTeamUsers = [];
    }
    appBosch.myTeamUsers.forEach(function(teamUser) {
        if (teamUser.nomina === nomina) {
            exist = true;
        }
    });
    return exist;
}

function showDlgInsertErrors( data ){
    $('#dlgU').html('');
    var dlgWindow = $("#dlgU").kendoWindow({
        title: "Detalles de la alta de usuarios",
        modal:true,
        visible: false, //the window will not appear before its .open method is called
        width: 350,
        height: 90
    }).data("kendoWindow");
    dlgWindow.content(appBosch.dlgTemplateAddErrors(data)); //send the row data object to the template and render it
    dlgWindow.open().center();  
}